package org.dizena.common.except;

import lombok.extern.slf4j.Slf4j;
import org.dizena.common.interaction.response.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.PrintWriter;
import java.io.StringWriter;

@Slf4j
@RestControllerAdvice
public class ExceptionAdviceHandler {
    private ApplicationEventPublisher publisher;

    @Autowired
    public void setPublisher(ApplicationEventPublisher publisher) {
        this.publisher = publisher;
    }


    @ExceptionHandler(value = BusinessException.class)
    public ResultVO handlerBusinessException(BusinessException e) {
        // publisher.publishEvent(new LogEvent(this,l));
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        log.error(sw.toString());
        return ResultVO.fail(e.getCode(), e.getMessage(),e.getData());
    }

    @ExceptionHandler(value = Exception.class)
    public ResultVO handlerException(Exception e) {
        // publisher.publishEvent(new LogEvent(this,l));
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        log.error(sw.toString());
        return ResultVO.fail(500, e.getMessage());
    }

}
